package com.jstyle.jclife.fragment;

import android.content.Context;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.activity.HeartTipsActivity;
import com.jstyle.jclife.adapter.HistoryHeartRangeAdapter;
import com.jstyle.jclife.adapter.HistoryShowAdapter;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.daoManager.UserInfoDaoManager;
import com.jstyle.jclife.model.HeartData;
import com.jstyle.jclife.model.UserInfo;
import com.jstyle.jclife.utils.ChartDataUtil;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.HealthDataUtils;
import com.jstyle.jclife.utils.ResolveData;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.view.HeatDetailDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;
import lecho.lib.hellocharts.view.PieChartView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HeartHistoryDayFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HeartHistoryDayFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.bt_sleep_week_pre)
    ImageView btSleepWeekPre;
    @BindView(R.id.bt_sleep_week_date)
    Button btSleepWeekDate;
    @BindView(R.id.bt_sleep_week_next)
    ImageView btSleepWeekNext;
    @BindView(R.id.iv_hr_levelHr_general)
    ImageView ivHrLevelHrGeneral;
    @BindView(R.id.iv_hr_levelHr_good)
    ImageView ivHrLevelHrGood;
    @BindView(R.id.iv_hr_levelHr_excellent)
    ImageView ivHrLevelHrExcellent;
    @BindView(R.id.iv_hr_levelHr_tooHigh)
    ImageView ivHrLevelHrTooHigh;
    //    @BindView(R.id.tv_max_heart)
//    TextView tvMaxHeart;
    @BindView(R.id.LineChartView_heart_day)
    LineChartView LineChartViewHeartDay;
    @BindView(R.id.bt_total_day)
    Button btTotalDay;
    @BindView(R.id.LineChartView_heart)//为复用报告布局
            RecyclerView RecyclerViewHeartDayTotal;
    @BindView(R.id.bt_heart_range)
    Button btHeartRange;
    @BindView(R.id.RecyclerView_heartRange)
    RecyclerView RecyclerViewHeartRange;
    @BindView(R.id.bt_heart_report)
    Button btHeartReport;

    @BindArray(R.array.color_heartReport_array)
    int[]heartReportColor;
    Unbinder unbinder;
    @BindString(R.string.heart_tips_0)
    String heartTips0;
    @BindString(R.string.heart_tips_1)
    String heartTips1;
    @BindString(R.string.heart_tips_2)
    String heartTips2;
    @BindString(R.string.heart_tips_3)
    String heartTips3;


    @BindView(R.id.tv_noData)
    Button tvNoData;
    @BindView(R.id.tv_result)
    TextView tvResult;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private String queryDate;
    private List<String> listContent;
    private HistoryShowAdapter historyShowAdapter;
    private Typeface mFace;
    private List<HeartData> heartDataList;

    public HeartHistoryDayFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.

     * @return A new instance of fragment HeartHistoryDayFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HeartHistoryDayFragment newInstance(String param1) {
        HeartHistoryDayFragment fragment = new HeartHistoryDayFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
       // args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
          //  mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_heart_history_day, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {

        mFace = Typeface.createFromAsset(getActivity().getAssets(), "Brandon_reg.otf");

        queryDate = TextUtils.isEmpty(mParam1)? DateUtil.getDefaultFormatTime(new Date()):mParam1;
        heartDataList = HeartDataDaoManager.queryDayData(queryDate);
        FlexboxLayoutManager layoutManager2 = new FlexboxLayoutManager(getActivity());
        listContent = new ArrayList<>();
        listContent.add(getString(R.string.avg_hr));
        listContent.add(getString(R.string.Minimum_HR));
        listContent.add(getString(R.string.Maximum_HR));
        historyShowAdapter = new HistoryShowAdapter(listContent);

        RecyclerViewHeartDayTotal.setAdapter(historyShowAdapter);
        RecyclerViewHeartDayTotal.setLayoutManager(layoutManager2);
        initData();
    }

    private void initHeartRange(int[] heartRanges) {//心率区间
        int total = 0;
        for (int i = 0; i < 5; i++) {
            total += heartRanges[i];
        }
        HistoryHeartRangeAdapter historyHeartRangeAdapter = new HistoryHeartRangeAdapter(getActivity(), heartRanges, total);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewHeartRange.setAdapter(historyHeartRangeAdapter);
        RecyclerViewHeartRange.setLayoutManager(linearLayoutManager);
    }


        private void getHeartReport(int[] heartRanges, int total) {
            float range0 = heartRanges[0];
            float range1 = heartRanges[1];
            float range2 = heartRanges[2];
            float range3 = heartRanges[3];
            float range4 = heartRanges[4];
            String tips = "";
            String level = "";
            ivHrLevelHrTooHigh.setVisibility(View.INVISIBLE);
            ivHrLevelHrExcellent.setVisibility(View.INVISIBLE);
            ivHrLevelHrGood.setVisibility(View.INVISIBLE);
            ivHrLevelHrGeneral.setVisibility(View.INVISIBLE);
            if (range4 >5 ||  (range3 + range4) > 20 || range3>20) {//过高
                tips = heartTips3;

                ivHrLevelHrTooHigh.setVisibility(View.VISIBLE);
            } else if ((range2>=20&&range2<=30) ||(range3 >=10&&range3<=20)|| (range4>0&&range4 <=5&&range3+range4>2 )||range2+range3>=20) {//优秀
                tips = heartTips2;

                ivHrLevelHrExcellent.setVisibility(View.VISIBLE);
            } else if ((range3>0&&range3<10&&range2+range3>2) ||(range2>5&&range2<20) ||range1+range2 +range3>30 ) {//良好
                tips = heartTips1;

                ivHrLevelHrGood.setVisibility(View.VISIBLE);
            } else {//弱
                tips = heartTips0;

                if (total != 0) ivHrLevelHrGeneral.setVisibility(View.VISIBLE);
            }
            tvResult.setText(tips);

            if(total==0)level=getString(R.string.No_data);
            //ChartDataUtil.setHeartPieChartView(ivResult,heartReportColor,level,pieValue,witdhCircle);


        }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.iv_hr_detail,R.id.bt_heart_range, R.id.bt_sleep_week_pre, R.id.bt_sleep_week_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_hr_detail:
                showHrDetail();
                break;
            case R.id.bt_heart_range:
                startActivity(HeartTipsActivity.class, HeartTipsActivity.TipsType, HeartTipsActivity.TipsType_ActivityHeart);
                break;
            case R.id.bt_sleep_week_next:
                queryDate = DateUtil.getTomorrowDateString(queryDate);
                initData();
                break;
            case R.id.bt_sleep_week_pre:
                queryDate = DateUtil.getYesterdayDateString(queryDate);
                initData();
                break;
        }
    }
    private void showHrDetail() {
        HeatDetailDialog heatDetailDialog=new HeatDetailDialog(getContext(),heartDataList,DateUtil.getShowDay(getActivity(), queryDate),R.style.jstyleDialog_style);
        heatDetailDialog.show();


    }
    private void initData() {
        btSleepWeekDate.setText(DateUtil.getShowDay(getActivity(), queryDate));
        String nowDate = DateUtil.getDefaultFormatTime(new Date());
        btSleepWeekNext.setEnabled(!queryDate.equals(nowDate));
        List<HeartData> heartDataList = HeartDataDaoManager.queryDayData(queryDate);

        String account = NetWorkUtil.getUserId();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(account);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(account);
            UserInfoDaoManager.insertUser(userInfo);
        }
        String birthday = userInfo.getBirthday();
        int userYear = Integer.parseInt(birthday.split("-")[0]);
        Calendar calendar = Calendar.getInstance();
        int age = calendar.get(Calendar.YEAR) - userYear;
        int MHR = 220 - age;
        int[] heartRanges = new int[5];
        int maxDayHr = 0;
        int minDayHr = 300;
        int totalDayHr = 0;
        int count = 0;
        for (int i = 0; i < heartDataList.size(); i++) {
            HeartData heartData = heartDataList.get(i);
            String date = heartData.getTime();
            int startCount = DateUtil.getMIndex(date, queryDate.split(" ")[0] + " 00:00:00",1);
            int heartRate = heartData.getHeart();
            // if (startCount >= 1440) break;
            if (heartRate != 0) {
                count++;
                totalDayHr += heartRate;
                maxDayHr = Math.max(maxDayHr, heartRate);
                minDayHr = Math.min(minDayHr, heartRate);
            }

        }

        int[] heartArray = new int[1440];//24*60分钟
        for (int i = 0; i < heartDataList.size(); i++) {
            HeartData heartData = heartDataList.get(i);
            String date = heartData.getTime();
            int startCount = DateUtil.getMIndex(date, queryDate.split(" ")[0] + " 00:00:00",1);
            int heartRate = heartData.getHeart();
            if (startCount >= 1440) break;
            if(heartRate!=0){
                int level = HealthDataUtils.getHeartRange(heartRate);
                heartRanges[level]++;
                heartArray[startCount]=heartRate;
            }
        }
        initHeartRange(heartRanges);
        getHeartReport(heartRanges, count);
        tvNoData.setVisibility(count == 0 ? View.VISIBLE : View.GONE);

        List<String> listHeart = new ArrayList<>();//总计列表
        int avgHR = count == 0 ? 0 : totalDayHr / count;
        listHeart.add(avgHR + " "+getString(R.string.hr_laber));
        listHeart.add((minDayHr == 300 ? 0 : minDayHr) + " "+getString(R.string.hr_laber));
        listHeart.add(maxDayHr + " "+getString(R.string.hr_laber));
        historyShowAdapter.setStepData(listHeart);

        float top=0;
        if(maxDayHr%10==0){
            top=maxDayHr;
        }else{
            top=(((int)maxDayHr/10)+1)*10;
        }
        if (count == 0) {
            LineChartViewHeartDay.setVisibility(View.INVISIBLE);
        } else {
            LineChartViewHeartDay.setVisibility(View.VISIBLE);
            ChartDataUtil.initDataChartView(LineChartViewHeartDay, -0.5f, top+10, heartArray.length, 40);
            LineChartViewHeartDay.setLineChartData(ChartDataUtil.getHistoryHeartDayChart(getActivity(), heartArray, mFace,0,top));
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
